package com.moodincode.taskcenter.job;

import com.moodincode.taskcenter.bean.TaskInfo;
import com.moodincode.taskcenter.script.ScriptInjectUtil;
import com.moodincode.taskcenter.service.IQuartzTaskService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.util.StringUtils;

import javax.script.ScriptEngine;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 脚本引擎定时器
 * @author moodincode
 */
@Slf4j
public class JavaScriptJob extends QuartzJobBean {

    @Autowired
    private IQuartzTaskService quartzTaskService;
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        long start = System.currentTimeMillis();
        JobKey jobKey = context.getTrigger().getJobKey();
        TaskInfo task = quartzTaskService.getTaskByJobKey(jobKey.getName(), jobKey.getGroup());
        if(task==null){
            log.error("找不到任务信息,jobKey name={},group={}",jobKey.getName(),jobKey.getGroup());
            return;
        }
        //判断是否要待执行的js脚本
        if(!StringUtils.hasText(task.getScript())){
            log.error("找不到任务信息待执行的js脚本,jobKey name={},group={}",jobKey.getName(),jobKey.getGroup());
            //写入日志
            writeLog(task,"失败","js脚本为空",start);
            return;
        }
        ScriptEngine scriptEngine = ScriptInjectUtil.getScriptEngine();
        //注入变量工具类
        ScriptInjectUtil.injectJavaClass(scriptEngine);
        try {
            //插入日志
            scriptEngine.put("log",log);
            scriptEngine.eval(task.getScript());
            //写入日志
            writeLog(task,"成功","定时任务执行成功",start);
        } catch (Exception e) {
           log.error("脚本执行异常,原因:",e);
            //写入日志
            writeLog(task,"失败","定时任务执行失败,原因"+e+e.getMessage(),start);
        }
    }

    /**
     * 写入日志
     * @param task
     * @param level
     * @param msg
     * @param startTimes
     */
    private void writeLog(TaskInfo task,String level,String msg,long startTimes){
        long endTimes = System.currentTimeMillis();
        long diff=endTimes-startTimes;
        Date date = new Date(endTimes);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        //拼接日志格式
        String log="【"+simpleDateFormat.format(date)+"】【"+level+"】："+msg+", 耗时:"+diff+"毫秒";
        List<String> logs = task.getLogs();
        if(logs.size()>9){
            logs.remove(0);
        }
        logs.add(log);
        task.setLogs(logs);
        task.setExecute(task.getExecute()+1);
        quartzTaskService.save(task);
    }
}
